<template>
    <div class="profile-container">


        <el-tabs v-model="activeTab" class="profile-tabs">
            <!-- 个人信息标签页 -->
            <el-tab-pane label="个人信息" name="info">
                <div class="info-section">
                    <div class="avatar-section">
                        <div class="avatar-wrapper">
                            <el-avatar :size="100" :src="userForm.avatar || userInfo.avatar"
                                icon="el-icon-user-solid"></el-avatar>
                            <div class="avatar-actions">
                                <el-upload class="avatar-uploader" :action="uploadAction" :show-file-list="false"
                                    :before-upload="beforeAvatarUpload" :http-request="handleAvatarUpload"
                                    accept="image/*">
                                    <el-button size="small" type="primary" :loading="uploadingAvatar">
                                        {{ uploadingAvatar ? '上传中...' : '更换头像' }}
                                    </el-button>
                                </el-upload>
                            </div>
                        </div>
                    </div>

                    <el-form ref="infoForm" :model="userForm" :rules="infoRules" label-width="120px" class="info-form">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="用户名" prop="username">
                                    <el-input v-model="userForm.username" :disabled="!editMode"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="账号" prop="account">
                                    <el-input v-model="userForm.account" disabled></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="手机号" prop="phone">
                                    <el-input v-model="userForm.phone" :disabled="!editMode"
                                        placeholder="请输入手机号"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="角色">
                                    <el-tag :type="getRoleType(userForm.role)">{{ getRoleText(userForm.role)
                                        }}</el-tag>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="状态">
                                    <el-tag :type="userForm.status === 1 ? 'success' : 'danger'">
                                        {{ userForm.status === 1 ? '正常' : '禁用' }}
                                    </el-tag>
                                </el-form-item>
                            </el-col>
                        </el-row>


                        <el-form-item>
                            <el-button v-if="!editMode" type="primary" @click="enableEdit">编辑信息</el-button>
                            <template v-else>
                                <el-button type="primary" @click="saveUserInfo" :loading="saving">保存</el-button>
                                <el-button @click="cancelEdit">取消</el-button>
                            </template>
                        </el-form-item>
                    </el-form>
                </div>
            </el-tab-pane>

            <!-- 修改密码标签页 -->
            <el-tab-pane label="修改密码" name="password">
                <div class="password-section">
                    <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="120px"
                        class="password-form">
                        <el-form-item label="原密码" prop="originPassword">
                            <el-input v-model="passwordForm.originPassword" type="password" placeholder="请输入原密码"
                                show-password></el-input>
                        </el-form-item>

                        <el-form-item label="新密码" prop="newPassword">
                            <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码"
                                show-password></el-input>
                        </el-form-item>

                        <el-form-item label="确认密码" prop="confirmPassword">
                            <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码"
                                show-password></el-input>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="changePassword"
                                :loading="changingPassword">修改密码</el-button>
                            <el-button @click="resetPasswordForm">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { updatePassword, updateUserInfo } from '@/api/user'
import { uploadAvatar } from '@/api/upload'

export default {
    name: 'Profile',
    data() {
        // 密码验证规则
        const validateNewPassword = (rule, value, callback) => {
            const reg = /^\d{6,15}$/
            if (!value) {
                callback(new Error('请输入新密码'))
            } else if (!reg.test(value)) {
                callback(new Error('密码必须为纯数字,6-15位'))
            } else {
                callback()
            }
        }

        const validateConfirmPassword = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.passwordForm.newPassword) {
                callback(new Error('两次输入的密码不一致'))
            } else {
                callback()
            }
        }

        return {
            activeTab: 'info',
            editMode: false,
            saving: false,
            changingPassword: false,
            uploadingAvatar: false,
            uploadAction: '', // 上传地址占位符

            // 用户信息表单
            userForm: {
                username: '',
                account: '',
                phone: '',
                role: '',
                status: 1,
                avatar: ''
            },

            // 原始用户信息（用于取消编辑时恢复）
            originalUserForm: {},

            // 密码修改表单
            passwordForm: {
                originPassword: '',
                newPassword: '',
                confirmPassword: ''
            },

            // 个人信息验证规则
            infoRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号码', trigger: 'blur' }
                ]
            },

            // 密码修改验证规则
            passwordRules: {
                originPassword: [
                    { required: true, message: '请输入原密码', trigger: 'blur' },
                    { pattern: /^\d{6,15}$/, message: '密码必须为纯数字,6-15位', trigger: 'blur' }
                ],
                newPassword: [
                    { required: true, validator: validateNewPassword, trigger: 'blur' }
                ],
                confirmPassword: [
                    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
                ]
            }
        }
    },

    computed: {
        ...mapGetters(['userInfo'])
    },

    created() {
        this.loadUserInfo()
    },

    methods: {
        // 加载用户信息
        loadUserInfo() {
            // 从store中获取用户信息
            this.userForm = {
                username: this.userInfo.username || '',
                account: this.userInfo.account || '',
                phone: this.userInfo.phone || '',
                role: this.userInfo.role || '',
                status: this.userInfo.status || 1,
                avatar: this.userInfo.avatar || ''
            }
            // 保存原始数据
            this.originalUserForm = { ...this.userForm }
        },

        // 启用编辑模式
        enableEdit() {
            this.editMode = true
        },

        // 取消编辑
        cancelEdit() {
            this.editMode = false
            this.userForm = { ...this.originalUserForm }
            this.$refs.infoForm.clearValidate()
        },

        // 保存用户信息
        async saveUserInfo() {
            this.$refs.infoForm.validate(async (valid) => {
                if (valid) {
                    this.saving = true
                    try {
                        // 调用更新用户信息的API
                        const response = await updateUserInfo(this.userForm)

                        if (response.code === 200) {
                            this.$message.success('个人信息更新成功')
                            this.editMode = false
                            this.originalUserForm = { ...this.userForm }

                            // 更新store中的用户信息
                            this.$store.commit('user/SET_USERINFO', this.userForm)
                        } else {
                            this.$message.error(response.msg || '更新失败')
                        }

                    } catch (error) {
                        console.error('更新用户信息失败:', error)
                        this.$message.error('更新失败，请重试')
                    } finally {
                        this.saving = false
                    }
                }
            })
        },

        // 修改密码
        async changePassword() {
            this.$refs.passwordForm.validate(async (valid) => {
                if (valid) {
                    this.changingPassword = true
                    try {
                        const requestData = {
                            originPassword: this.passwordForm.originPassword,
                            newPassword: this.passwordForm.newPassword
                        }

                        const response = await updatePassword(requestData)

                        if (response.code === 200) {
                            this.$message.success('密码修改成功，请重新登录')
                            this.resetPasswordForm()
                            // 密码修改成功后退出登录
                            setTimeout(() => {
                                this.$store.dispatch('user/logout')
                                this.$router.push('/login')
                            }, 1500)
                        } else {
                            this.$message.error(response.msg || '密码修改失败')
                        }
                    } catch (error) {
                        console.error('修改密码失败:', error)
                        this.$message.error('密码修改失败，请重试')
                    } finally {
                        this.changingPassword = false
                    }
                }
            })
        },

        // 重置密码表单
        resetPasswordForm() {
            this.passwordForm = {
                originPassword: '',
                newPassword: '',
                confirmPassword: ''
            }
            this.$refs.passwordForm && this.$refs.passwordForm.resetFields()
        },

        // 上传前验证
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
                return false
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!')
                return false
            }
            return true
        },

        // 自定义头像上传
        async handleAvatarUpload(options) {
            const { file } = options

            if (!this.beforeAvatarUpload(file)) {
                return
            }

            this.uploadingAvatar = true

            try {
                // 创建FormData对象
                const formData = new FormData()
                formData.append('file', file)

                // 调用上传API
                const response = await uploadAvatar(formData)

                if (response.code === 200) {
                    // 上传成功，更新头像URL
                    this.userForm.avatar = response.data
                    this.$message.success('头像上传成功')

                    // 如果在编辑模式，自动保存
                    if (this.editMode) {
                        await this.saveUserInfo()
                    } else {
                        // 不在编辑模式时，只更新头像
                        await this.updateAvatarOnly()
                    }

                    // 重新获取用户信息以确保数据同步
                    await this.refreshUserInfo()
                } else {
                    this.$message.error(response.msg || '头像上传失败')
                }
            } catch (error) {
                console.error('头像上传失败:', error)
                this.$message.error('头像上传失败，请重试')
            } finally {
                this.uploadingAvatar = false
            }
        },

        // 只更新头像
        async updateAvatarOnly() {
            try {
                const avatarData = {
                    avatar: this.userForm.avatar
                }
                const response = await updateUserInfo(avatarData)
                if (response.code === 200) {
                    // 更新store中的用户信息
                    this.$store.commit('user/SET_USERINFO', {
                        ...this.userInfo,
                        avatar: this.userForm.avatar
                    })
                    this.originalUserForm.avatar = this.userForm.avatar
                }
            } catch (error) {
                console.error('更新头像失败:', error)
                this.$message.error('保存头像失败')
            }
        },

        // 重新获取用户信息
        async refreshUserInfo() {
            try {
                // 调用store中的获取用户信息方法
                await this.$store.dispatch('user/getInfo')
                // 重新加载本地用户信息
                this.loadUserInfo()
            } catch (error) {
                console.error('刷新用户信息失败:', error)
            }
        },

        // 获取角色类型
        getRoleType(role) {
            const types = {
                'admin': 'danger',
                'teacher': 'warning',
                'student': 'success'
            }
            return types[role] || 'info'
        },

        // 获取角色文本
        getRoleText(role) {
            const texts = {
                'admin': '管理员',
                'teacher': '教师',
                'student': '学生'
            }
            return texts[role] || '未知'
        }
    }
}
</script>

<style lang="scss" scoped>
.profile-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0;
}

.profile-card {
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
}

.profile-header {
    text-align: center;

    h2 {
        margin: 0 0 8px 0;
        color: #303133;
        font-size: 24px;
        font-weight: 600;
    }

    p {
        margin: 0;
        color: #909399;
        font-size: 14px;
    }
}

.profile-tabs {
    margin-top: 20px;

    ::v-deep .el-tabs__header {
        margin-bottom: 30px;
    }

    ::v-deep .el-tabs__item {
        font-size: 16px;
        font-weight: 500;
    }
}

.info-section {
    .avatar-section {
        text-align: center;
        margin-bottom: 40px;

        .avatar-wrapper {
            display: inline-block;

            .avatar-actions {
                margin-top: 15px;

                .avatar-uploader {
                    display: inline-block;
                }
            }
        }
    }

    .info-form {
        max-width: 800px;
        margin: 0;
    }
}

.password-section {
    .password-form {
        max-width: 500px;
        margin: 0;
        padding: 20px;
    }
}

// 响应式设计
@media (max-width: 768px) {
    .profile-container {
        padding: 10px;
    }

    .info-form,
    .password-form {
        max-width: 100%;
    }

    .el-col {
        margin-bottom: 10px;
    }
}
</style>
